package com.chess;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ChessServiceThread extends Thread{
	
	private Socket socket;
	private boolean isPlaying = false;
	private PrintWriter writer;
	private BufferedReader reader;
	private ChessServiceThread partnerThread;
	
	public ChessServiceThread(Socket socket) {
		this.socket = socket;
		try {
			writer = new PrintWriter(socket.getOutputStream());
			reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public boolean isPlaying() {
		return isPlaying;
	}

	public void setPlaying(boolean isPlaying) {
		this.isPlaying = isPlaying;
	}

	@Override
	public void run() {
		while(!isPlaying);
		while(true) {
			try {
				String message = reader.readLine();
				if(message == null) {
					partnerThread.send("exit");
					System.out.println(message);
					break;
				}
				partnerThread.send(message);
				
			} catch (IOException e) {
				partnerThread.send("exit");
				e.printStackTrace();
				break;
			}
		}
	}
	
	public void send(String message) {
		writer.println(message);
		writer.flush();
	}

	public ChessServiceThread getPartnerThread() {
		return partnerThread;
	}

	public void setPartnerThread(ChessServiceThread partnerThread) {
		this.partnerThread = partnerThread;
	}
}
